// projects/oa/pages/sample/detail/sample_detail.js
// 导入路径辅助模块，避免重复引用
const pathImport = require('../helpers/path_import.js');
const { pageHelper, cloudHelper } = pathImport;;
const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { sampleStore } = require('../../../config/store_config.js');

// 调试模式开关
const DEBUG_MODE = true;

// 调试数据
const DEBUG_DATA = {
	sample: {
		_id: 'debug_1',
		SAMPLE_NAME: '调试样品1',
		SAMPLE_CODE: 'DBG001',
		SAMPLE_VERSION: 'V1.0',
		SAMPLE_CUSTOMER: '测试客户',
		SAMPLE_PROJECT_IDS: ['proj_001'],
		SAMPLE_PROJECT_NAMES: '项目A',
		SAMPLE_STATUS: 1,
		statusDesc: '调试中',
		SAMPLE_LOCATION: '测试位置',
		SAMPLE_MAKE_USER_ID: 'user_001',
		engineerName: '测试工程师',
		SAMPLE_NOTES: '这是一个测试样品的详细说明',
		createTime: '2024-01-01',
		SAMPLE_ATTACHMENTS: [
			'/projects/oa/images/banner/banner1.jpg',
			'/projects/oa/images/banner/banner2.jpg',
			'/projects/oa/images/banner/banner3.jpg'
		]
	}
};

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		isLoad: false,
		id: '',
		sample: null,
		canModify: false,
		isFullScreen: false,
		currentViewImg: ''
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		ProjectBiz.initPage(this);
		
		if (!options || !options.id) {
			pageHelper.showNoneToast('样品ID参数错误');
			setTimeout(() => {
				wx.navigateBack();
			}, 1500);
			return;
		}

		// 创建MobX绑定
		this.storeBindings = createStoreBindings(this, {
			store: sampleStore,
			fields: [
				'currentSample',
				'sampleDetail',
				'loading'
			],
			actions: [
				'loadSampleDetail'
			]
		});

		if (DEBUG_MODE) {
			this.setData({
				isLoad: true,
				sample: DEBUG_DATA.sample,
				canModify: true
			});
			// 设置当前样品以保持一致性
			sampleStore.currentSample = DEBUG_DATA.sample;
			sampleStore.sampleDetail = DEBUG_DATA.sample;
			return;
		}
		
		// 加载样品详情
		await this.loadSampleDetail(options.id);
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
		// 销毁绑定
		if (this.storeBindings) {
			this.storeBindings.destroyStoreBindings();
		}
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: async function () {
		await this._loadDetail();
		wx.stopPullDownRefresh();
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	},

	/**
	 * 加载详情
	 */
	_loadDetail: async function (id) {
		try {
			const detail = await cloudHelper.callCloudData('sample/detail', { id });
			
			if (detail) {
				this.setData({
					isLoad: true,
					sample: detail
				});
			}
		} catch (err) {
			console.error('加载详情失败：', err);
		}
	},

	/**
	 * 检查权限
	 */
	_checkPermission: async function() {
		try {
			if (DEBUG_MODE) {
				console.log('调试模式：跳过权限检查');
				this.setData({
					canModify: true
				});
				wx.showToast({
					title: '调试模式：权限检查已暂时忽略',
					icon: 'none',
					duration: 2000
				});
				return;
			}

			let res = await cloudHelper.callCloudData('sample/check');
			this.setData({
				canModify: res
			});
		} catch (err) {
			console.error('权限检查失败:', err);
			if (DEBUG_MODE) {
				this.setData({
					canModify: true
				});
				wx.showToast({
					title: '调试模式：权限检查已暂时忽略',
					icon: 'none',
					duration: 2000
				});
			} else {
				this.setData({
					canModify: false
				});
			}
		}
	},

	/**
	 * 预览图片
	 */
	bindPreviewImage: function(e) {
		let urls = e.currentTarget.dataset.urls;
		let current = e.currentTarget.dataset.current;
		wx.previewImage({
			current,
			urls
		});
	},

	/**
	 * 全屏查看图片
	 */
	bindFullScreenView: function(e) {
		const img = e.currentTarget.dataset.img;
		this.setData({
			isFullScreen: true,
			currentViewImg: img
		});
	},

	/**
	 * 关闭全屏
	 */
	bindCloseFullScreen: function() {
		this.setData({
			isFullScreen: false,
			currentViewImg: ''
		});
	},

	/**
	 * 返回
	 */
	bindBack: function() {
		wx.navigateBack();
	},

	/**
	 * 编辑样品
	 */
	bindEditTap: function() {
		const id = this.data.currentSample._id;
		wx.navigateTo({
			url: '../edit/sample_edit?id=' + id
		, timeout: 10000, fail: function(err) {
        // 处理超时错误
        if (err.errMsg && err.errMsg.includes("timeout")) {
          wx.showToast({
            title: "页面加载超时，请重试",
            icon: "none"
          });
          return;
        }
        
        // 处理其他错误
        console.error("页面跳转失败:", err);
        wx.showToast({
          title: "页面跳转失败",
          icon: "none"
        });
      }});
	},

	/**
	 * 删除样品
	 */
	bindDeleteTap: async function () {
		const that = this;
		const callback = async () => {
			try {
				await cloudHelper.callCloudData('sample/delete', {
					id: that.data.sample._id
				});
				
				pageHelper.showSuccToast('删除成功', 1500);
				setTimeout(() => {
					wx.navigateBack();
				}, 1500);
			} catch (err) {
				console.error('删除失败：', err);
			}
		};

		pageHelper.showConfirm('确定删除？删除后不可恢复', callback);
	},

	url: function(e) {
		pageHelper.url(e, this);
	}
})